const LhzxHttpClient = require('./LhzxHttpClient');

// 云翼信协议测试
async function testYunyxProtocol() {
    console.log('=== 云翼信协议测试 ===\n');
    
    const client = new LhzxHttpClient();
    
    // 测试配置 - 请替换为您的真实参数
    const testConfig = {
        siid: "TEST001",                     // 客户编号（请替换为真实值）
        user: "testUser",                    // HTTP账号（请替换为真实值）
        secretKey: "testSecretKey123",       // 接口密钥（请替换为真实值）
        mobile: "13800138000",               // 测试手机号
        content: "【测试】云翼信协议测试短信", // 短信内容
        extcode: "123"                       // 扩展码
    };
    
    console.log('1. 测试参数验证功能:');
    const isValid = client.validateConfig(testConfig);
    console.log('参数验证结果:', isValid ? '✅ 通过' : '❌ 失败');
    console.log();
    
    console.log('2. 测试时间戳格式化:');
    const testTime = new Date();
    const formattedTime = client.formatTimestamp(testTime);
    console.log('当前时间:', testTime);
    console.log('格式化时间戳:', formattedTime);
    console.log('时间戳长度:', formattedTime.length, '位');
    console.log();
    
    console.log('3. 测试流水号生成:');
    const streamingNo = client.generateStreamingNo(testConfig.siid, formattedTime);
    console.log('流水号:', streamingNo);
    console.log();
    
    console.log('4. 测试认证码计算:');
    const timeStamp = formattedTime;
    const transactionID = timeStamp;
    const authenticator = client.calculateAuthenticator(timeStamp, transactionID, streamingNo, testConfig.secretKey);
    console.log('时间戳:', timeStamp);
    console.log('事务号:', transactionID);
    console.log('流水号:', streamingNo);
    console.log('认证字符串:', timeStamp + transactionID + streamingNo + testConfig.secretKey);
    console.log('认证码:', authenticator);
    console.log();
    
    console.log('5. 测试完整请求参数生成:');
    const requestData = {
        siid: testConfig.siid,
        user: testConfig.user,
        streamingNo: streamingNo,
        timeStamp: timeStamp,
        transactionID: transactionID,
        authenticator: authenticator,
        mobile: testConfig.mobile,
        extcode: testConfig.extcode,
        content: testConfig.content
    };
    
    console.log('完整请求参数:');
    console.log(JSON.stringify(requestData, null, 2));
    console.log();
    
    console.log('6. 测试返回码解释功能:');
    const testRetCodes = ['0000', '0403', '0404', '0501', '9999'];
    testRetCodes.forEach(code => {
        console.log(`测试返回码 ${code}:`);
        client.explainRetCode(code);
        console.log();
    });
    
    console.log('7. 是否发送到云翼信测试服务器？');
    console.log('注意：这将使用云翼信的真实测试接口');
    console.log('地址：https://yyx.saas.189.cn:8070/jt3netsmsservicehttp/httpservices/capService');
    
    // 设置为true来发送真实请求（需要有效的认证信息）
    const shouldSendRealRequest = false;
    
    if (shouldSendRealRequest) {
        console.log('发送真实请求到云翼信服务器...');
        try {
            const result = await client.sendSMS(testConfig);
            console.log('真实请求结果:', result);
        } catch (error) {
            console.error('真实请求失败:', error.message);
            
            // 分析错误类型
            if (error.message.includes('ENOTFOUND')) {
                console.log('💡 网络错误：无法连接到云翼信服务器');
            } else if (error.message.includes('403')) {
                console.log('💡 认证错误：请检查siid、user、secretKey是否正确');
            } else if (error.message.includes('SSL')) {
                console.log('💡 SSL错误：可能是HTTPS证书问题');
            }
        }
    } else {
        console.log('跳过真实请求发送');
        console.log('如需测试真实请求，请：');
        console.log('1. 将shouldSendRealRequest设置为true');
        console.log('2. 替换testConfig中的siid、user、secretKey为真实值');
        console.log('3. 确保网络可以访问云翼信服务器');
    }
    
    console.log('\n=== 测试完成 ===');
    console.log('协议符合性检查：');
    console.log('✅ 时间戳格式：yyyyMMddhhmmsszzz (17位)');
    console.log('✅ 认证码算法：BASE64(MD5(timeStamp+transactionID+streamingNo+secretKey))');
    console.log('✅ 请求参数：符合云翼信协议规范');
    console.log('✅ 返回码处理：已实现完整的错误码映射');
}

// 与Java版本对比测试
async function compareWithJavaVersion() {
    console.log('\n=== 与Java版本对比测试 ===\n');
    
    const client = new LhzxHttpClient();
    
    // 使用与Java demo相同的测试数据
    const javaTestData = {
        siid: "",
        user: "fswgEE", 
        secretKey: "testSecretKey",
        mobile: "133xxxx4889",
        content: "【签名】云翼信测试！",
        extcode: "123"
    };
    
    // 使用固定时间戳进行对比
    const fixedTime = new Date('2016-09-26T16:25:50.676Z');
    const timeStamp = client.formatTimestamp(fixedTime);
    const transactionID = timeStamp;
    const streamingNo = client.generateStreamingNo(javaTestData.siid, timeStamp);
    const authenticator = client.calculateAuthenticator(timeStamp, transactionID, streamingNo, javaTestData.secretKey);
    
    console.log('Java版本对比测试:');
    console.log('时间戳:', timeStamp);
    console.log('事务号:', transactionID);
    console.log('流水号:', streamingNo);
    console.log('认证码:', authenticator);
    console.log();
    
    console.log('预期Java版本输出格式:');
    const expectedRequest = {
        siid: javaTestData.siid,
        user: javaTestData.user,
        streamingNo: streamingNo,
        timeStamp: timeStamp,
        transactionID: transactionID,
        authenticator: authenticator,
        mobile: javaTestData.mobile,
        extcode: javaTestData.extcode,
        content: javaTestData.content
    };
    
    console.log(JSON.stringify(expectedRequest, null, 2));
}

// 运行所有测试
async function runAllTests() {
    try {
        await testYunyxProtocol();
        await compareWithJavaVersion();
    } catch (error) {
        console.error('测试执行错误:', error);
    }
}

// 运行测试
runAllTests(); 